<?php

class post_handler extends _site_handler {
	public $Errors;
	public $Type;
	public $Id;
	public $PostId;
	public $FormBody = '';
	public $FormTitle = '';
	public $FormUrl;
	public $FormId;

	public function __construct($m, $view) {
		$this->InitializeSite($m);
		$this->Wordlets->AddWordlets('post');
		$this->Type = @$_GET['type'];
		$this->Id = @$_GET['id'];
		$this->PostId = @$_GET['post_id'];

		if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
			$success = false;
			if ( $_SESSION['form_id'] != $_POST['form_id'] ) {
				$this->Errors['form'][] = $this->Wordlets->Get('error_form_already_submitted');
			} else {
				$_SESSION['form_id'] = NULL;
				$success = Post::CreateUpdate($params = array(
					'target_type' => @$_GET['type'],
					'target_id' => @$_GET['id'],
					'title' => @$_POST['title'],
					'body' => @$_POST['body'],
					'post_id' => @$_GET['post_id'],
				));
			}

			if ( !$success ) {
				if ( !$this->Errors ) {
					$errors = Post::Errors();
	
					foreach ( $errors as $key => $es ) {
						foreach ( $es as $v ) {
							$this->Errors[$key][] = $this->Wordlets->Get($key);
						}
					}
				}

				$this->FormBody = htmlspecialchars(@$_POST['body']);
				$this->FormTitle = htmlspecialchars(@$_POST['title']);
			} elseif ( @$_POST['test'] ) {
				$this->RenderViewContent('success');
				exit;
			} else {
				header("Location: " . (($_GET['back_url'])?$_GET['back_url']:'/'));
				exit;
			}
		}

		$_SESSION['form_id'] = time();
		$this->FormId = $_SESSION['form_id'];

		$this->FormUrl = $_SERVER['REQUEST_URI'];

		$this->RenderViewContent($view);
	}
}
